//
//  YRComposePictureView.swift
//  新浪微博
//
//  Created by Viper on 16/7/3.
//  Copyright © 2016年 Viper. All rights reserved.
//

import UIKit
private let PictureViewCellId = "pictureViewCellId"
class YRComposePictureView: UICollectionView {

    var composePircureViewClosure :(()->())?
    
    var imageList : [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - 设置视图
    private func  setupUI(){
        
        hidden = true
        
        backgroundColor = UIColor.clearColor()
        
        dataSource = self
        
        delegate = self
        //注册cell
        registerClass(YRComposePictureViewCell.self, forCellWithReuseIdentifier: PictureViewCellId)
        
        //设置layout
        let layout = collectionViewLayout as? UICollectionViewFlowLayout

        //设置item
        let itemMargin : CGFloat = 5
        let cellWH = (SCREENW - 20 - itemMargin*2)/3
        layout?.itemSize = CGSize(width: cellWH, height: cellWH)
        
        //设置垂直和水平间距
        layout?.minimumLineSpacing = itemMargin
        
        layout?.minimumInteritemSpacing = itemMargin
        
    }
    //MARK: - 供外界调用的方法
    func addImages(image : UIImage){
        
        imageList.insert(image, atIndex: 0)
        //如果count大于9  删除最后一张图片
        if imageList.count > 9 {
            
            imageList.removeLast()
            
        }
        
        hidden = false
        //刷新
        reloadData()
    }
    
    /*
     如果有四张图面 显示5个cell 最后一张是加号图片
     如果有0或者9张图片 没有加号 九张显示九个cell
     
     */
    
}
extension YRComposePictureView : UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = imageList.count
        
        if  count == 0 || count == 9 {
            
            return count
            
        }else{
            
            return imageList.count + 1
            
        }
        
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureViewCellId, forIndexPath: indexPath) as! YRComposePictureViewCell
        //设置cell背景se
//        cell.backgroundColor = RandomColor()、
        if imageList.count == indexPath.item {
            
            cell.image = nil
            
            
        }else{
            
            cell.image = imageList[indexPath.item]
            
        }
        //实现删除按钮闭包
        cell.deleteButtonClosure = {
            //删除指定数组
            self.imageList.removeAtIndex(indexPath.item)
            if self.imageList.count == 0 {
                
             self.hidden = true
            }
            
            //刷新UI
            self.reloadData()
        }
        
            return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //如果数组的count==indexPath.item就是加号按钮
        
        if imageList.count == indexPath.item {
            
//            print("加号按钮")
            composePircureViewClosure?()
        }
        
    }
    
 
    
}
//自定义cell
class YRComposePictureViewCell: UICollectionViewCell {
    //声明删除按钮闭包
    var deleteButtonClosure:(()->())?
    
    //供外界赋值
    var image : UIImage?{
        
        didSet{
            if image == nil {
                
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                //隐藏删除按钮
                deleteButton.hidden = true
            }else{
                
                bgImageView.image = image
            //解决cell重用问题
                bgImageView.highlightedImage = nil
                //显示删除按钮
                deleteButton.hidden = false
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 监听事件
    
    @objc private func deleteBtnClick(){
        
//        print("删除按钮点击了")
        //调用删除按钮闭包
        deleteButtonClosure?()
        
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        //添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(deleteButton)
        //添加约束
        bgImageView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteButton.snp_makeConstraints { (make) in
            
            make.top.equalTo(contentView)
            make.trailing.equalTo(contentView)
            
        }
        
        
    }
    //MARK: - 懒加载控件
    private lazy var bgImageView : UIImageView = UIImageView()
    //删除按钮
    private lazy var deleteButton : UIButton = {
       
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.addTarget(self, action: #selector(YRComposePictureViewCell.deleteBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
        return button
        
    }()
    
    
}



